package com.web.action;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.hibernate.util.SystemConstant;
import com.mytest.model.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.service.UserService;
import com.util.ActionConstant;

public class LoginAction extends ActionSupport
{
    /**
     * 
     */
    private static final long serialVersionUID = -350789381638395680L;
    private String	    userName;
    private String	    password;
    private String	    result;
    
    private UserService 	userService;

    /** 
     * @Title: login方法
     * @Description: 系统登录<br/>
     * @return
     * @throws Exception    
     * @return String    返回类型
     */
    public String login() throws Exception{
		try {
		    //获得ActionContext实例，访问Servlet　API
		    ActionContext ctx = ActionContext.getContext();
		    if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
			    addActionMessage("用户名或密码不能为空，请重新输入。");
		    	return ActionConstant.INPUT;
		    } else {
				List<User> userList = userService.findUser(userName, password);
				if(userList!=null&&userList.size()==1){
				    User sessionUser = userList.get(0);
		
				    //user添加到session中
				    ctx.getSession().put(SystemConstant.SESSION_USER, sessionUser);
				    ctx.getSession().put(SystemConstant.SESSION_USER_ID, sessionUser.getUserId());
				    ctx.getSession().put(SystemConstant.SESSION_USER_EMAIL, sessionUser.getUserEmail());
		
				    return ActionConstant.SUCCESS;//登录成功
				} else {
				    addActionMessage("用户名或密码错误，请重新输入。");
				    return ActionConstant.INPUT;
				}
		    }
		} catch (Exception e) {
		    //操作发生异常，记入数据库
		    return ActionConstant.ERROR;
		}
    }

    public String getUserName(){
	return userName;
    }

    public void setUserName(String userName){
	this.userName = userName;
    }

    public String getPassword(){
	return password;
    }

    public void setPassword(String password){
	this.password = password;
    }

    public String getResult(){
	return result;
    }

    public void setResult(String result){
	this.result = result;
    }

    public UserService getUserService(){
        return userService;
    }

    public void setUserService(UserService userService){
        this.userService = userService;
    }
}